Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example: Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.


In [33]:
class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        nums_len = len(nums)
        i, j = 0, 0
        while j < nums_len:
            if nums[j] != val:
                nums[i] = nums[j]
                i += 1
            j += 1
        return i

In [34]:
Solution().removeElement([1], 1)


Out[34]:
0

In [3]:
class Solution:
    # @param    A       a list of integers
    # @param    elem    an integer, value need to be removed
    # @return an integer
    # clrs qsort
    def removeElement(self, A, elem):
        """
            这种方法是将target的值倒序放到后面
            虽然保全整个数组的完整性,但是数组
            的元素顺序并不是原来的顺序了
            
        """
        j = len(A)-1
        for i in range(len(A) - 1, -1, -1):
            if A[i] == elem:
                A[i], A[j] = A[j], A[i]
                j -= 1
                print(A)
        return j+1

In [5]:
Solution().removeElement([3, 2, 4, 3, 5, 6, 8], 3)


[3, 2, 4, 8, 5, 6, 3]
[6, 2, 4, 8, 5, 3, 3]
Out[5]:
5

In [ ]: